package cn.good.yan.config.demo3;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.util.HashMap;

/**
 * 三
 * 【用户认证 - 前后端分离】
 * 认证失败 - 处理逻辑
 * 演示：
 * 1. 进行登录：http://localhost:8080/login
 * 2. 输入错误的密码，会返回下面的 HashMap 所封装的数据
 * 3。正确，会进入 MyAuthenticationSuccessHandler 过滤器
 *
 * @author shengren.yan
 * @create 2024-07-24
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        //获取错误信息
        String localizedMessage = exception.getLocalizedMessage();

        //创建结果对象
        HashMap<String, Object> result = new HashMap();
        result.put("code", -1);
        result.put("data", "自定义错误信息");
        result.put("message", localizedMessage);

        //转换成json字符串
        String json = JSON.toJSONString(result);

        //返回响应
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }

}
